package com.qk.management.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.dto.activity.ActivityListDTO;
import com.qk.entity.Activity;
import com.qk.entity.Clue;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author diva
 * @date 2025/10/9 14:53
 * @ProjectName
 */
@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ClueMapper clueMapper;

    @Override
    public PageResult<Activity> list(ActivityListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Activity> list = activityMapper.selectByPage(dto);
        Page<Activity> page = (Page<Activity>) list;
        return PageResult.<Activity>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
    @Override
    public void delete(Integer id) {
        log.info("删除活动：{}",id);
        List<Clue> clue = clueMapper.selectList(Wrappers.lambdaQuery(Clue.class).eq(Clue::getActivityId, id));
        if(!clue.isEmpty()){
            log.error("该活动{}有线索引用，请先删除线索", id);
            CommonException.throwException(ParamEnum.ACTIVITY_REFERENCE_ERROR);
        }
        activityMapper.delete(id);
    }

    @Override
    public void add(Activity activity) {
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.insert(activity);
    }
    @Override
    public Activity getActivityById(Integer id) {
        return activityMapper.selectByPrimaryKey(id);
    }
    @Override
    public void update(Activity activity) {
        activityMapper.updateByPrimaryKeySelective(activity);
    }
    @Override
    public List<Activity> getActivityByType(Integer type) {
        return activityMapper.selectByType(type);
    }

}
